<?php

/* 
 * 首页控制器
 */
namespace Home\Controller;

use \Common\Lib\Sms\Sms;

class IndexController extends HomeController {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        /**
         * banner滚动区开始
         */
        $slider = M('Slider')->where(['code' => 'banner_index'])->find();
        $sliderItems = [];
        if (!empty($slider)) {
            $sliderItems = M('SliderItem')->where([
                'slider_id' => $slider['id'],
                'status' => 1,
                'start_time' => ['lt', time()],
                'end_time' => ['gt', time()]
            ])->order('sort ASC,id DESC')->select();
        }
        /**
         * banner滚动区结束
         */

        //公告
        $category = M('ArticleCategory')->where(['alias' => 'annouce'])->find();
        $annouce = [];
        if ($category) {
            $annouce = M('Article')->where(['categroy_id' => $category['id']])->order('id DESC')->limit(3)->select();
        }

        //商家活动
        $ac_where = [];
        $ac_where['show_index'] = 1;
        $ac_where['status'] = 1;
        $ac_where['begin_time'] = ['lt', time()];
        $ac_where['end_time'] = ['gt', time()];
        $activity = M('SupplierActivity')->where($ac_where)->order('id DESC')->limit(2)->select();

        //热卖推荐
        $hot = M('Goods')->where(['hot' => 1, 'shelves' => 1])->order('sort ASC,sales DESC,id DESC')->limit(3)->select();

        //每周上新
        $newest = M('Goods')->where(['newest' => 1, 'shelves' => 1])->order('sort ASC,id DESC')->limit(5)->select();

        //主题馆
        $theme = M('GoodsCategory')->where(['is_theme' => 1, 'status' => 1])->order('sort ASC,id DESC')->limit(9)->select();

        //猜你喜欢
        $fav = M('Goods')->where(['recommend' => 1, 'shelves' => 1])->order('sort ASC,id DESC')->limit(4)->select();

        $this->assign([
            'fav' => $fav,
            'theme' => $theme,
            'newest' => $newest,
            'hot' => $hot,
            'activity' => $activity,
            'sliderItems' => $sliderItems,
            'annouce' => $annouce,
        ]);
        $this->display();
    }

    public function cap() {
        if (empty($_SERVER['HTTP_REFERER'])) {
            exit('');
        }

        $mobile = I('mobile', '', 'trim');
        if (empty($mobile)) {
            $this->error('手机号错误');
        }
        if (IS_POST) {
            $captcha = I('cap', '', 'trim');
            if (!$this->check_verify($captcha)) {
                $this->error('验证码错误');
            } else {
                $cache = 'sms_send_' . $mobile;
                if (isMobile($mobile)) {
                    if (!S($cache)) {
                        $result = $this->sms($mobile);
                        if ($result['status'] == 'success') {
                            S($cache, time(), 60);
                            session('sms_mobile', $mobile);
                            $this->success("短信已发送至{$mobile}");
                        }
                        file_put_contents('./sms_error.txt', $result['errmsg']);
                        $this->error('短信发送失败' . $result['status']);
                    } else {
                        $this->error('发送短信过于频繁，稍微再试');
                    }
                } else {
                    $this->error('手机号格式错误');
                }
            }
        } else {
            $has_mobile = M('User')->where(['mobile' => $mobile])->count();
            if ($has_mobile > 0) {
                $this->assign('error', $mobile . '该手机号已使用');
            } else {
                $this->assign('mobile', $mobile);
            }
            $this->display();
        }
    }


    public function forget() {
        $ses = session('mobile_sms');

        if (IS_POST) {
            $forget_type = I('forget_type');
            $captcha = I('captcha');

            $user = array();
            if (!$this->check_verify($captcha)) {
                $this->error('验证码错误', 876);
            }

            if ($forget_type == 'mobile') {
                $mobile = I('mobile');
                $mobile_sms = I('mobile_sms', 0, 'intval');

                if (!isMobile($mobile)) {
                    $this->error('手机格式错误');
                }

                if (session('sms_mobile') != $mobile) {
                    $this->error('请使用接受验证码的手机号' . $mobile . '==' . session('sms_mobile'));
                }

                if ($mobile_sms != session('mobile_sms')) {
                    $this->error('手机验证码错误');
                }

                $user = M('User')->where(array('mobile' => $mobile))->find();

            } elseif ($forget_type == 'email') {
                $email = I('email');
                if (!isEmail($email)) {
                    $this->error('邮箱格式错误');
                }

                $email_code = I('email_code', 0, 'intval');
                if ($email_code != session('forget_email')) {
                    $this->error('邮箱验证码错误');
                }

                $user = M('User')->where(array('email' => $email))->find();
            }

            if (empty($user)) {
                $this->error('该用户不存在');
            } else {
                session(array('name' => 'forget_user', 'expire' => 180));
                session('forget_user', $user[id]);
                $this->success(array('url' => U('Index/reset')), 'ok');
                exit;
            }

        } else {
            $this->display();
        }
    }

    //发送邮件
    public function send_email() {
        $email = I('email');
        if (!isEmail($email)) {
            $this->error('邮箱格式错误');
        }
        $user = M('User')->where(array('email' => $email))->count();
        if (empty($user)) {
            $this->error('该用户不存在');
        }

        $code = mt_rand(111111, 999999);
        session(array('name' => 'forget_email', 'expire' => 600));
        session('forget_email', $code);
        $content = '用户找回密码，验证码' . $code . '，有效期10分钟';

        if ($this->send_mail($email, $content)) {
            $this->success('邮件已发送');
        }

        $this->error('邮件发送失败');
    }

    //重置密码
    public function reset() {
        $uid = session('forget_user');
        if (empty($uid)) {
            $this->error('验证码已过期，请重新操作', U('Index/forget'));
        }
        $user = M('User')->find($uid);
        if (empty($user)) {
            session('forget_user', null);
            $this->error('该用户不存在', U('Index/forget'));
        }

        if (IS_POST) {
            $password = I('password');
            $passwordr = I('passwordr');
            if (empty($password)) {
                $this->error('密码不能为空');
            }
            if ($password != $passwordr) {
                $this->error('两次密码输入不一致');
            }

            $new_password = entrypt_password($password);
            M('User')->where(array('id' => $uid))->setField('password', $new_password);
            session('forget_user', null);
            $this->success(array('url' => U('/login')), '密码修改成功');
        } else {
            $this->display();
        }
    }

    public function test() {

        $Ali = new AliUpdateController();
        if ($Ali->doesObjectExist('dir/dahangqingddd.png') === true) {
            echo '1';
        } else {
            echo '不存在或发生错误' . $Ali->getError();
        }
        $listObjectInfo = $Ali->listObjects();
//        
//        $objectList = $listObjectInfo->getObjectList(); // 文件列表
//        $prefixList = $listObjectInfo->getPrefixList(); // 目录列表
//        if (!empty($objectList)) {
//            print("objectList:\n");
//            foreach ($objectList as $objectInfo) {
//                print($objectInfo->getKey() . "\n");
//            }
//        }
//        if (!empty($prefixList)) {
//            print("prefixList: \n");
//            foreach ($prefixList as $prefixInfo) {
//                print($prefixInfo->getPrefix() . "\n");
//            }
//        }

//        if($Ali->deleteObject('dir/a.gif')){
//            echo '文件删除成功';
//            
//        }else{
//           echo $Ali->getError(); 
//        }
//        if($Ali->putObject('dir/dahangqing.png','./6.jpg') !== false){
//            echo '文件上传成功';
//        }else{
//            echo $Ali->getError();
//        }
//        if($Ali->createObjectDir('images') !== false){
//            echo '目录创建成功';
//        }else{
//            echo $Ali->getError();
//        }
    }
}